import loguru
from loguru import logger

from . mongoDBManage import get_mongo_database, get_mongo_collection
from . dbuitl import objectIDtoStr,strToObjectID

def getDocumentFromID(tableName, ID):
    """
    根据表名和ObjectID查询唯一文档
    :param tableName: 数据库表名称
    :param ID: 字符串id
    :return: 标准json格式
    """
    pcttdb = get_mongo_database()
    collection = pcttdb[tableName]
    logger.debug("dao层从{}表搜索id{}".format(tableName, ID))
    result = collection.find_one({'_id': strToObjectID(ID)})
    return objectIDtoStr(result)


def getAllDocument(tableName):
    pass


def pageQuery(tableName, queryFilter=None, pageNumber=1, pageSize=20):
    """
    Pymongo的分页查询
    :param tableName:数据库表名称
    :param queryFilter: 查询语句
    :param pageNumber: 当前页
    :param pageSize:   页大小
    :return:
    """
    print('pagenumber',pageNumber)
    pageNumber = int(pageNumber)
    pageSize = int(pageSize)
    skip = pageSize * (pageNumber - 1)
    collection = get_mongo_collection(tableName)
    print("数据条数",queryFilter)
    # 返回数据总条数
    if queryFilter:
        logger.info("从集合{}中查询条件{}".format(tableName,queryFilter))
        total = collection.count_documents(queryFilter)
        # total = collection.find().estimated_document_count()
    else:
        logger.info("查询所有条件")
        total = sum(1 for _ in collection.find())
        # print(dir(collection.find()))
        # total = collection.find().estimated_document_count()
        #

    page_result = collection.find(queryFilter).limit(pageSize).skip(skip)
    resultList = [objectIDtoStr(doc) for doc in page_result]
    return resultList, total


def fuzzySearch(tableName, keyword, value):
    """
    TODO: 同步Mongo数据到ES中，支持全文搜索、迁移等需求

    :param tableName:数据库表名称
    :param keyword: key值
    :param value: value值
    :return:
    """
    pcttdb = get_mongo_database()
    collection = pcttdb[tableName]
    collection.find({keyword: {'$regex': '.*{}.*'.format(value)}}, ).limit(100)
    pass


if __name__ == '__main__':
    print(strToObjectID("61dfd99d5b7bb6e4aa67226d"))
